package org.spring.boot.fusion.common.tools;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;

import ch.ethz.ssh2.ChannelCondition;
import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.Session;
import ch.ethz.ssh2.StreamGobbler;

public class ShellTool {

	private Connection conn;
	/** 远程机器IP */
	private String ip;
	/** 用户名 */
	private String usr;
	/** 密码 */
	private String psword;
	/**端口 */
	private int port;
	
	private String charset = Charset.defaultCharset().toString();

	private static final int TIME_OUT = 1000 * 5 * 60;

	public ShellTool(String ip,int port,String userName, String passWord) {
		this.ip = ip;
		this.usr = userName;
		this.psword = passWord;
		this.port=port;
	}
	
	public ShellTool login(String ip,int port,String userName, String passWord){
		return new ShellTool(ip,port,userName,passWord);
	}

	private boolean login() throws IOException {
		conn = new Connection(ip,port);
		conn.connect();
		return conn.authenticateWithPassword(usr, psword);
	}

	public int exec(String cmds) throws Exception {
		InputStream stdOut = null;
		InputStream stdErr = null;
		String outStr = "";
		String outErr = "";
		int ret = -1;
		try {
			if (login()) {
				Session session = conn.openSession();
				session.execCommand(cmds);

				stdOut = new StreamGobbler(session.getStdout());
				outStr = processStream(stdOut, charset);

				stdErr = new StreamGobbler(session.getStderr());
				outErr = processStream(stdErr, charset);

				session.waitForCondition(ChannelCondition.EXIT_STATUS, TIME_OUT);

				System.out.println("outStr=" + outStr);
				System.out.println("outErr=" + outErr);

				ret = session.getExitStatus();
			} else {
				throw new RuntimeException("登录远程机器失败" + ip);
			}
		} finally {
			if (stdOut != null) {
				stdOut.close();
			}
			if (stdErr != null) {
				stdErr.close();
			}
			if (conn != null) {
				conn.close();
			}
		}
		return ret;
	}

	private String processStream(InputStream in, String charset) throws Exception {
		byte[] buf = new byte[1024];
		StringBuilder sb = new StringBuilder();
		while (in.read(buf) != -1) {
			sb.append(new String(buf, charset));
		}
		return sb.toString();
	}
}  